package com.example.springbootjwt.controller;

import com.example.springbootjwt.annotation.PassLogin;
import com.example.springbootjwt.bean.User;
import com.example.springbootjwt.dao.UserMapper;
import com.example.springbootjwt.http.ResponseResult;
import com.example.springbootjwt.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

@CrossOrigin
@RestController
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JwtUtil jwtUtil;

    @RequestMapping("/login")
    @PassLogin
    public ResponseResult login(Model model, String username, String password, HttpServletRequest request, HttpServletResponse response) throws IOException {
        User user = new User(username, password);
        int i = userMapper.login(user);
        if (i > 0) {
            String token = jwtUtil.createToken("1111", "1");
            response.setHeader(jwtUtil.getHeader(), "Bearer " + token);

            return ResponseResult.ok().setMsg(token);
        } else {
            return ResponseResult.invalid_request().setMsg("用户名或密码错误");
        }
    }

    @RequestMapping("/parse")
    public ResponseResult next(HttpServletRequest request, HttpServletResponse response) {
        String header = request.getHeader("Authorization");
        Claims claims = jwtUtil.parseToken(header);
        System.out.println(claims.getSubject());
        return ResponseResult.ok(claims.getSubject());
    }


    /*
     * 测试自定义登录头请求
     * */
    @RequestMapping("/tologin")
    public String reslogin(Model model, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        String header = request.getHeader("Authorization");
        System.out.println(header);
        return "success";
    }

}
